import { reactive, ref, unref } from "vue"
import axios from "axios"
//导入element-plus 提示框
import { ElMessage } from "element-plus"
//导入路由
import router from "@/router"

export const useEnroll = () => {
  const ruleFormRef = ref()

  const validatePass = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请输入密码"))
    } else {
      if (newUserForm.confirmPassword !== "") {
        if (!ruleFormRef.value) return
        ruleFormRef.value.validateField("confirmPassword", () => null)
      }
      callback()
    }
  }
  const validatePass2 = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请再次输入密码"))
    } else if (value !== newUserForm.password) {
      callback(new Error("两次密码不一致"))
    } else {
      callback()
    }
  }

  const newUserForm = reactive({
    username: "",
    password: "",
    confirmPassword: "",
  })
  //表单验证
  const newUserRules = reactive({
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ validator: validatePass, trigger: "blur" }],
    confirmPassword: [{ validator: validatePass2, trigger: "blur" }],
  })

  //点击注册用户
  const enrollForm = () => {
    const form = unref(ruleFormRef)
    if (!form) return
    //如果验证不通过,清空input框
    //  form.resetFields()
    //整体表单验证
    form.validate((valid) => {
      if (valid) {
        //检测成功
        //获取所有用户,判断用户名是否已经存在
        axios.get("http://localhost:3000/ggusers").then((res) => {
          // console.log(res.data.result);
          const { dataB } = res.data.result
          let arr = dataB.map((item) => {
            return item.user_name
          })
          if (arr.indexOf(newUserForm.username) != -1) {
            ElMessage.error("用户名已经存在")
             //如果验证不通过,清空input框
            form.resetFields()
          } else {
            //不存在,发送请求,添加用户
            axios.post("http://localhost:3000/ggusers", {
              user_name: newUserForm.username,
              user_password: newUserForm.password,
              user_type: "",
            }).then((res)=>{
              console.log(res);
            })
            router.push("/login/logon")
            ElMessage.success("注册成功")
          }
        })
      }
    })
  }

  return { newUserForm, newUserRules, ruleFormRef, enrollForm }
}
